package com.dynamic.mybatis.core.generator.method;

import com.dynamic.mybatis.core.generator.AbstractMethod;
import com.dynamic.mybatis.core.generator.InjectorHelper;
import com.dynamic.mybatis.core.generator.MapperMethod;
import com.dynamic.mybatis.core.generator.helper.LogicDeleteHelper;
import com.dynamic.mybatis.core.generator.helper.SelectInjectorHelper;
import com.dynamic.mybatis.core.metadata.DynamicMappedStatement;
import com.dynamic.mybatis.core.metadata.MappedStatementMetaField;
import com.dynamic.mybatis.core.metadata.MappedStatementTable;
import com.dynamic.mybatis.core.parser.NamespaceHelper;
import org.apache.ibatis.builder.MapperBuilderAssistant;
import org.apache.ibatis.executor.keygen.NoKeyGenerator;
import org.apache.ibatis.mapping.MappedStatement;
import org.apache.ibatis.mapping.SqlCommandType;
import org.apache.ibatis.mapping.SqlSource;
import org.apache.ibatis.scripting.defaults.RawSqlSource;
import org.apache.ibatis.session.Configuration;

import java.util.Map;
import java.util.Optional;

/**
 * @Description
 * @Author xs
 * @Date 2023/4/14 10:12
 */
public class SelectById extends AbstractMethod {

    public SelectById() {
        super(MapperMethod.StandardMapperMethod.selectById);
    }

    @Override
    public String builderScriptSql(String namespace, MappedStatementTable table, MapperBuilderAssistant assistant) {

        Optional<MappedStatementMetaField> optionalKeyField = InjectorHelper.getFirstKeyField(table);

        String keyColumn = optionalKeyField.isPresent() ? optionalKeyField.get().getColumn() : null;
        String keyField = optionalKeyField.isPresent() ? optionalKeyField.get().getField() : null;

        String sql = String.format(getSqlTemplate(),
                SelectInjectorHelper.sqlSelectColumns(table, false),
                table.getTableName(), keyColumn, keyField,
                LogicDeleteHelper.getLogicDeleteSql(table, true, true));
        return sql;
    }

    @Override
    public DynamicMappedStatement injectMappedStatement(String tenantCode,String namespace, MappedStatementTable table, MapperBuilderAssistant assistant) {
        Configuration configuration = assistant.getConfiguration();

        String sql = builderScriptSql(namespace, table, assistant);
        String msNamespace = NamespaceHelper.getNamespace(tenantCode,namespace);

        SqlSource sqlSource = new RawSqlSource(configuration, sql, Map.class);

        MappedStatement ms = super.addMappedStatement(assistant, table, msNamespace, sqlSource, SqlCommandType.SELECT, Map.class, null, Map.class, NoKeyGenerator.INSTANCE, null, null);

        return builderDynamicMappedStatement(tenantCode,namespace, table, ms, sql);
    }
}